package com.mall507.fivepeaks.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.hzh.frame.BaseInitData;
import com.hzh.frame.comn.annotation.ContentView;
import com.hzh.frame.comn.annotation.ViewInject;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.BaseSP;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.activity.BaseUI;
import com.hzh.frame.util.AndroidUtil;
import com.hzh.frame.util.PowerUtil;
import com.hzh.frame.util.StatusBarUtil;
import com.hzh.frame.widget.xdialog.XDialogUpdateAPP;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.activity.community.CommunityRFM;
import com.mall507.fivepeaks.activity.find.FindRFM;
import com.mall507.fivepeaks.activity.main.MainRFM;
import com.mall507.fivepeaks.activity.mine.MineFM;
import com.mall507.fivepeaks.activity.release.ReleaseFM;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import q.rorbin.badgeview.QBadgeView;

@Route(path = "/main/MainUI")
@ContentView(R.layout.ui_main)
public class MainUI extends BaseUI{

    @ViewInject(R.id.bottomNavigationView) BottomNavigationView mBottomNavigationView;
    @ViewInject(R.id.viewPager) ViewPager mViewPager;

    private MainRFM mMainFM=new MainRFM();
    private CommunityRFM mCommunityRFM=new CommunityRFM();
    private ReleaseFM mReleaseFM=new ReleaseFM();
    private FindRFM mFindFM=new FindRFM();
    private MineFM mMineFM=new MineFM();

    private QBadgeView mQBadgeView=new QBadgeView(BaseInitData.applicationContext);

    @Override
    public boolean setTitleIsShow() {
        return false;
    }

    @Override
    protected void onCreateBase() {
        StatusBarUtil.setTransparentForImageView(this,null);

        mViewPager.setOffscreenPageLimit(5);
        mViewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
        mViewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        mBottomNavigationView.setOnNavigationItemSelectedListener(new MyOnNavigationItemSelectedListener());
        mBottomNavigationView.setItemIconTintList(null);
        getUpgrade();
        //权限申请延时2000秒
        Flowable.timer(2000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        powerApply();
                        Log.w("timer","timer");
                    }
                });
    }

    class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:return mMainFM;
                case 1:return mCommunityRFM;
                case 2:return mReleaseFM;
                case 3:return mFindFM;
                case 4:return mMineFM;
                default: return null;
            }
        }
        @Override
        public int getCount() {
            return 5;
        }
    }


    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener{
        @Override
        public void onPageScrolled(int i, float v, int i1) {}
        @Override
        public void onPageScrollStateChanged(int i) {}
        @Override
        public void onPageSelected(int position) {
            mBottomNavigationView.getMenu().getItem(position).setChecked(true);
        }
    }

    //这里可true是一个消费过程，同样可以使用break，外部返回true也可以
    class MyOnNavigationItemSelectedListener implements BottomNavigationView.OnNavigationItemSelectedListener {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.main:
                    mViewPager.setCurrentItem(0);
                    return true;
                case R.id.type:
                    mViewPager.setCurrentItem(1);
                    return true;
                case R.id.store:
                    mViewPager.setCurrentItem(2);
                    return true;
                case R.id.car:
                    mViewPager.setCurrentItem(3);
                    return true;
                case R.id.mine:
                    mViewPager.setCurrentItem(4);
                    return true;
            }
            return true;
        }
    }


    /**暂时找不到问题了为了防止下级页面调用 MainUI方法崩溃*/
    public void dayOnClick(View view){}

    public XDialogUpdateAPP updateAPPDialog;//APP升级弹窗
    // 从服务器获取最新版本
    private void getUpgrade() {
        BaseHttp.getInstance().query("", null, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (1==response.optInt("code")) {
                    JSONObject data = response.optJSONObject("data");
                    int versionCode=data.optInt("VERSION");
                    String[] versionNames=(versionCode+"").trim().split("");
                    String versionName="V ";
                    for(int i=0;i<versionNames.length;i++){
                        //第一表 || 最后一个 (注:不加逗号)
                        if(i == 0 || i == (versionNames.length-1)){
                            versionName = versionName + versionNames[i];
                        } else {
                            versionName = versionName + versionNames[i] + ".";
                        }
                    }
                    if (versionCode > AndroidUtil.getVersionCode(MainUI.this)) {
                        updateAPPDialog=new XDialogUpdateAPP(MainUI.this)
                                .setFileName("FivePeaks.apk")
                                .setMsg(data.optString("MSG"))
                                .setAppDownUrl(data.optString("URL").trim())
                                .setUpdataVersionCode(versionName);
                        updateAPPDialog.show();
                    }
                }
            }
        });
    }



    private long exitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) // System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                alert("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                //伪 退出
                //                moveTaskToBack(true);
                //真 退出
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //权限申请
    public void powerApply(){
        /**
         * 申请APP所需的权限(申请后系统会回调一个传入Activity的onRequestPermissionsResult)
         * 获取精确位置    android.permission.ACCESS_FINE_LOCATION，通过GPS芯片接收卫星的定位信息，定位精度达10米以内   
         * */
        String[] permissions=new String[]{/*Manifest.permission.READ_PHONE_STATE,*/Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION};
        if(!PowerUtil.selectApply(this,permissions)){
            PowerUtil.apply(this,100,permissions);
        }else{
            BaseSP.getInstance().put("powerApply",true);
        }
    }

    @Override
    //权限申请 | 结果回调
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(100==requestCode && permissions.length == grantResults.length){
            //判断每个权限的申请情况
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i] == PackageManager.PERMISSION_GRANTED){
                    Log.i(AndroidUtil.getPackageName()+"--->权限申请:","授权成功 | " + permissions[i]);
                    BaseSP.getInstance().put(permissions[i],true);//记录申请成功的权限
                    if(Manifest.permission.ACCESS_FINE_LOCATION.equals(permissions[i])){//定位权限申请成功
                    } else
                    if(Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[i])){//写入申请成功
                    }
                } else{
                    Log.i(AndroidUtil.getPackageName()+"--->权限申请:","授权失败 | " + permissions[i]);
                    BaseSP.getInstance().put(permissions[i],false);//记录申请失败的权限
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case XDialogUpdateAPP.INSTALL_PERMISS_CODE://安装未知应用来源的权限通过,安装APK
                    if(updateAPPDialog!=null) updateAPPDialog.openApk();
                    break;
                case ReleaseFM.REQUEST_CROP:// 发布页面 | 裁剪图片
                    mReleaseFM.onFramentResult(requestCode,data);
                    break;
            }
        }
    }


    /**
     * BottomNavigationView隐藏角标
     * @param viewIndex tab索引
     */
    private void hideBadgeView(int viewIndex) {
        // 具体child的查找和view的嵌套结构请在源码中查看
        // 从bottomNavigationView中获得BottomNavigationMenuView
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) mBottomNavigationView.getChildAt(0);
        // 从BottomNavigationMenuView中获得childview, BottomNavigationItemView
        if (viewIndex < menuView.getChildCount()) {
            // 获得viewIndex对应子tab
            View view = menuView.getChildAt(viewIndex);
            // 显示badegeview
            mQBadgeView.bindTarget(view).hide(false);
        }
    }


    /**
     * BottomNavigationView显示角标
     * @param viewIndex tab索引
     * @param showNumber 显示的数字，小于等于0是将不显示
     */
    private void showBadgeView(int viewIndex, int showNumber) {
        // 具体child的查找和view的嵌套结构请在源码中查看
        // 从bottomNavigationView中获得BottomNavigationMenuView
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) mBottomNavigationView.getChildAt(0);
        // 从BottomNavigationMenuView中获得childview, BottomNavigationItemView
        if (viewIndex < menuView.getChildCount()) {
            // 获得viewIndex对应子tab
            View view = menuView.getChildAt(viewIndex);
            // 显示badegeview
            mQBadgeView.bindTarget(view).setGravityOffset(10, 3, false).setBadgeNumber(showNumber);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mMainFM.setUserVisibleHint(mMainFM.getUserVisibleHint());
        mCommunityRFM.setUserVisibleHint(mCommunityRFM.getUserVisibleHint());
        mReleaseFM.setUserVisibleHint(mReleaseFM.getUserVisibleHint());
        mFindFM.setUserVisibleHint(mFindFM.getUserVisibleHint());
        mMineFM.setUserVisibleHint(mMineFM.getUserVisibleHint());
    }
}
